package com.pig4cloud.pig.ads.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.ads.service.AdAccountService;
import com.pig4cloud.pig.ads.service.AdAccountWarningResultService;
import com.pig4cloud.pig.ads.service.AdAccountWarningSettingService;
import com.pig4cloud.pig.api.dto.AdAccountWarningSettingDTO;
import com.pig4cloud.pig.api.entity.*;
import com.pig4cloud.pig.api.vo.AdAccountWarnVo;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 广告账户提醒Controller
 * @Author chengang
 * @Date 2021/7/13
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "warning")
@Api(value = "warning", tags = "不活跃广告账户预警模块")
public class AdAccountWarningController {

	private final AdAccountWarningSettingService adAccountWarningSettingService;

	private final AdAccountWarningResultService adAccountWarningResultService;

	private final AdAccountService adAccountService;

	private final RemoteUserService remoteUserService;

	@PreAuthorize("@pms.hasPermission('INACTIVE_ACCOUNT_RULE_SETTING')")
	@SysLog("不活跃规则设定")
	@PostMapping("setting")
	public R setting(@RequestBody @Valid AdAccountWarningSettingDTO dto){
		//基础校验 使用 @Valid https://blog.csdn.net/u012102104/article/details/78956639
		AdAccountWarningSetting setting = new AdAccountWarningSetting();
		setting.setDays(dto.getDays());
		setting.setUsers(dto.getUsers());
		setting.setTimes(dto.getTimes());
		//默认没有发生邮件 1没有 2已发送
		setting.setIsSend(1);
		Integer userId = SecurityUtils.getUser().getId();
		setting.setCreateId(Long.valueOf(userId));
		setting.setUpdateId(Long.valueOf(userId));
		//保留每一次设定的历史记录  is_delete = 1
		AdAccountWarningSetting hasSetting = adAccountWarningSettingService.getOne(Wrappers.<AdAccountWarningSetting>query()
				.lambda().eq(AdAccountWarningSetting::getIsDeleted,0));
		if (hasSetting != null) {
			// 任一设定条件修改均重新开始统计不活跃账号并发送邮件
			hasSetting.setIsDeleted(1);
			adAccountWarningSettingService.updateById(hasSetting);
		}
		boolean result = adAccountWarningSettingService.save(setting);
		if (result) {
			adAccountWarningResultService.getNoActiveAccountList(userId);
			return R.ok();
		} else {
			return R.failed();
		}
	}

	@GetMapping("getInfo")
	public R getInfo(){
		AdAccountWarningSetting hasSetting = adAccountWarningSettingService.getOne(Wrappers.<AdAccountWarningSetting>query()
				.lambda().eq(AdAccountWarningSetting::getIsDeleted,0));
		return R.ok(hasSetting);
	}


	@SysLog("不活跃账户列表")
	@GetMapping(value = "getNoActiveList")
	public R getNoActiveList(Page page) {
		LambdaQueryWrapper<AdAccountWarningResult> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(AdAccountWarningResult::getIsDeleted, 0));
		query.and(wrapper -> wrapper.eq(AdAccountWarningResult::getActive, 2));
		query.orderByDesc(AdAccountWarningResult::getCreateTime);

		IPage<AdAccountWarningResult> listPage = adAccountWarningResultService.page(page, query);

		List<AdAccountWarningResult> list = listPage.getRecords();
		Map<String,Object> resultMap = Maps.newHashMap();
		int advertiserCount = 0;
		BigDecimal totalBalance = BigDecimal.ZERO;
		if (!CollectionUtils.isEmpty(list)) {

			List<String> ids = list.stream().map(AdAccountWarningResult::getAdvertiserId).filter(Objects::nonNull).collect(Collectors.toList());

			//当前页-获取无消耗累计天数
			//查询不到的账户表示该账户没有进行任何广告投放或投放没有任何曝光、点击等数据,此时无法计算该账户的无消耗累计天数 显示 '-'
			// 广告计划仅曝光，点击但没有消耗 则 cost==0
			//计算逻辑：1、(无论活跃)账号最大的时间 - 最小的时间 = 相隔的天数 2、相隔的天数 - 活跃的天数 = 不活跃的累计天数 3.不计算创建账号到第一次有记录之间的时间差
			List<AdAccountWarnVo> noCostList = adAccountWarningResultService.getNoCostCount(ids);

			//查询总数和总余额
			//广告名称、投放人名称分页查询改为全查询
			List<AdAccountWarningResult> totalList = adAccountWarningResultService.getNoActiveList();
			//设置各种名称
			totalBalance = adAccountWarningResultService.setNameAndAmount(totalList);

			//因账户不多暂不考虑分页查询
			//获取累计账户数量
			advertiserCount = totalList.size();

			list.forEach(warningResultVo -> {
				//设置无消耗累计天数-默认 "-"
				warningResultVo.setNoCostCount("-");
				if (!CollectionUtils.isEmpty(noCostList)) {
					noCostList.forEach(noCostAd -> {
						if (warningResultVo.getAdvertiserId().equals(noCostAd.getAdAccount())) {
							warningResultVo.setNoCostCount(noCostAd.getNoCostCount());
						}
					});
				}

				totalList.forEach(total -> {
					if (warningResultVo.getMediaType().equals(total.getMediaType())
						&& warningResultVo.getAdvertiserId().equals(total.getAdvertiserId())) {
						warningResultVo.setBalance(total.getBalance());
						warningResultVo.setThrowUser(total.getThrowUser());
						warningResultVo.setAdvertiserName(total.getAdvertiserName());
						// 现金可用余额 --划款用
						warningResultVo.setCashBalance(total.getCashBalance());
						// 赠款可用余额 --划款用
						warningResultVo.setGrantBalance(total.getGrantBalance());
					}
				});
			});
		}
		resultMap.put("page",listPage);
		resultMap.put("totalBalance",totalBalance);
		resultMap.put("advertiserCount",advertiserCount);
		return R.ok(resultMap);
	}

	@SysLog("不活跃规则-退款")
	@GetMapping("refund")
	public R refund (@RequestParam(value = "advertiserId") String advertiserId,
					 @RequestParam(value = "mediaType") Integer mediaType) {
		if (mediaType == null) {
			return R.failed("媒体不能为空");
		}
		if (StringUtils.isBlank(advertiserId)) {
			return R.failed("广告账户ID不能为空");
		}
		return adAccountWarningResultService.refund(mediaType,advertiserId);
	}

}
